package com.domain.dto;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
public class PageDTO<T> implements Serializable {

    @Schema(description = "当前页码", example = "1")
    protected Long pageIndex;

    @Schema(description = "每页显示最大数据条数", example = "10")
    protected Long pageSize;

    @Schema(description = "总条数", example = "100000")
    protected Long total;

    @Schema(description = "总页数", example = "100")
    protected Long pages;

    @Schema(description = "当前页数据列表")
    protected List<T> rows;
    public static <T, D> PageDTO<T> create(Page<D> page, DataTransCallBack<T, D> callback) {
        //初始化分页信息
        PageDTO<T> pageResult = new PageDTO<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setPageIndex(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setPages(page.getPages());
        //转换数据
        List<D> records = page.getRecords();
        if (records != null && !records.isEmpty()) {
            List<T> rows = new ArrayList<>();
            for (D sub : records) {
                try {
                    T t = callback.executeTrans(sub);
                    rows.add(t);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            pageResult.setRows(rows);
        }
        return pageResult;
    }
}
